package com.restaurant.application.scoreset;

import com.nebutown.base.ViewSpec;
import com.nebutown.base.data.View;
import com.nebutown.base.data.ViewUpdate;
import com.nebutown.commonunits.dataface.DataModes;
import com.nebutown.commonunits.dataface.FormShell;
import com.nebutown.commonunits.dataface.TableShell;
import com.nebutown.commonunits.dataface.definitions.*;
import com.nebutown.commonunits.uidataface.UIDataFace;
import com.nebutown.generation.basicdata.UIDRecord;
import com.nebutown.generation.basictype.StringData;
import com.nebutown.generation.basictype.UID;
import com.restaurant.application.score.Score;
import com.restaurant.application.score.support.ScoreData;
import com.restaurant.application.scoreset.support.AbstractScoreSet;
import com.restaurant.application.scoreset.support.ScoreSetPageData;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class ScoreSetImpl extends AbstractScoreSet {

    @Override
    public View getFullView() {
        return newCommonTable(new ScoreSetPageData(), 1);
    }

    @Override
    public View getViewLead(ViewSpec viewSpec) {
        return null;
    }

    @Override
    public ViewUpdate insert(int[] seq) {
        Score score = createNode(Score.class);
        return returnPushInContainer(score.getId(), false);
    }

    @Override
    public ViewUpdate search(ScoreSetPageData search, int[] seq) {
        return null;
    }

    @Override
    public ViewUpdate detail(int[] seq) {
        return null;
    }

    @Override
    public ViewUpdate edit(int[] seq) {
        return null;
    }

    @Override
    public ViewUpdate delete(int[] seq) {
        getData().getLists().remove(seq[0]);
        return returnView(newCommonTable(new ScoreSetPageData(), 1));
    }

    @Override
    public ViewUpdate switchPage(StringData switchPage, int[] seq) {
        return null;
    }

    private View newCommonTable(ScoreSetPageData search, int pageNum) {
        int pageSize = 10;
        List<UIDRecord> records = getData().getLists().getAll();
        int totalRecord = records.size();
        int totalPage = (totalRecord + pageSize + 1) / pageSize;
        List<UIDRecord> recordList = records.stream()
                .sorted(Comparator.comparing(x -> getUnit(Score.class, x.getUid()).findData().getModifyTime()))
                .skip(pageSize * (pageNum - 1))
                .limit(pageSize).collect(Collectors.toList());
        PageInfo pageInfo = new PageInfo()
                .withPageNum(pageNum)
                .withPageSize(pageSize)
                .withTotalPage(totalPage)
                .withTotalRecord(totalRecord)
                .withJumpPath(getPath(CMD_SWITCHPAGE));
        PageForm pageForm = newFormShell(recordList, pageInfo).getForm();
        return getSingleton(UIDataFace.class).newGenericForm(unitPosition(), pageForm);
    }

    private FormShell newFormShell(List<UIDRecord> recordList, PageInfo pageInfo) {

        FormShell formShell = new FormShell("门店积分设置", 3, 3);

        formShell.source(new ScoreSetPageData(), DataModes.EDIT);

        formShell.at(0, 2, "新增")
                .buttonField(getPath(CMD_INSERT), "", false);

        List<ScoreSetPageData> collect = recordList.stream().map(e -> {
            ScoreData scoreData = getUnit(Score.class, e.getUid()).findData();
            return new ScoreSetPageData().withShopId(scoreData.getShopId()).withShopName(scoreData.getShopName())
                    .withPaying(scoreData.getPaying()).withScore(scoreData.getScore())
                    .withSeq(Long.valueOf(e.getSeq()));
        }).collect(Collectors.toList());
        TableShell<ScoreSetPageData> tableShell = new TableShell<>(ScoreSetPageData.class, collect).withPageInfo(pageInfo);

        tableShell.createColumn(ScoreSetPageData.FN_SHOPID).withName("等级").cellCalculator(b -> {
            ScoreSetPageData bean = (ScoreSetPageData) b;
            return new CellData()
                    .withField(new FieldContent().withSimpleField(bean.getShopId() == null ? "" : bean.getShopId()));
        });
        tableShell.createColumn(ScoreSetPageData.FN_SHOPNAME).withName("名称").cellCalculator(b -> {
            ScoreSetPageData bean = (ScoreSetPageData) b;
            return new CellData()
                    .withField(new FieldContent().withSimpleField(bean.getShopName() == null ? "" : bean.getShopName()));
        });
        tableShell.createColumn(ScoreSetPageData.FN_PAYING).withName("消费金额").cellCalculator(b -> {
            ScoreSetPageData bean = (ScoreSetPageData) b;
            return new CellData()
                    .withField(new FieldContent().withSimpleField(bean.getPaying() == null ? "" : String.valueOf(bean.getPaying())));
        });
        tableShell.createColumn(ScoreSetPageData.FN_SCORE).withName("所得积分").cellCalculator(b -> {
            ScoreSetPageData bean = (ScoreSetPageData) b;
            return new CellData()
                    .withField(new FieldContent().withSimpleField(bean.getScore() == null ? "" : String.valueOf(bean.getScore())));
        });
        tableShell.createColumn("doSomething").withName("操作").cellCalculator(b -> {
            ScoreSetPageData bean = (ScoreSetPageData) b;
            return new CellData()
                    .withField(new FieldContent().withButton(new ButtonField().withLabel("查看").withButtonPath(getPath(CMD_DETAIL, bean.getSeq()))))
                    .withField(new FieldContent().withButton(new ButtonField().withLabel("编辑").withButtonPath(getPath(CMD_EDIT, bean.getSeq()))))
                    .withField(new FieldContent().withButton(new ButtonField().withLabel("删除").withButtonPath(getPath(CMD_DELETE, bean.getSeq()))));
        });

        formShell.at(2, 0, "门店积分设置")
                .large(3, 1)
                .getEntry("error", "")
                .tableEntry(tableShell);

        return formShell;
    }

    @Override
    public void addScore(UID id) {
        if (id != null) {
            getData().getLists().add(id);
        }
    }

    @Override
    public int findScoreByPaying(String shopId, double paying) {
        UID uid = getData().getLists().getAll().stream().filter(uidRecord -> {
            Score score = getUnit(Score.class, uidRecord.getUid());
            return shopId.equals(score.findData().getShopId());
        }).map(UIDRecord::getUid).findAny().orElse(null);
        if (uid == null) {
            getLogger().error("shopId is error!");
            return -1;
        }
        ScoreData scoreData = getUnit(Score.class, uid).findData();
        long l = (long) paying;
        return (int) (l * scoreData.getScore() / scoreData.getPaying());
    }
}
